<?php
//Calculate file size
function format_filesize($size, $round = 0) {
// -------------------------------------
//   Converts from a size in bytes to a friendly display size
// -------------------------------------
    $sizes = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
    for ($i = 0; $size > 1024 && isset($sizes[$i + 1]); $i++)
        $size /= 1024;
    return round($size, $round) . $sizes[$i];
}

//Get all files in a specified folder
function get_files($folder, $include_subs = FALSE) {
// Remove any trailing slash
    if (substr($folder, -1) == '/') {
        $folder = substr($folder, 0, -1);
    }

// Make sure a valid folder was passed
    if (!file_exists($folder) || !is_dir($folder) || !is_readable($folder)) {
        return FALSE;
        exit();
    }

// Grab a file handle
    $all_files = FALSE;
    if ($handle = opendir($folder)) {
        $all_files = array();
// Start looping through a folder contents
        while ($file = @readdir($handle)) {
// Set the full path
            $path = $folder . '/' . $file;

// Filter out this and parent folder
            if ($file != '.' && $file != '..') {
// Test for a file or a folder
                if (is_file($path)) {
                    $all_files[] = $path;
                } elseif (is_dir($path) && $include_subs) {
// Get the subfolder files
                    $subfolder_files = get_files($path, TRUE);

// Anything returned
                    if ($subfolder_files) {
                        $all_files = array_merge($all_files, $subfolder_files);
                    }
                }
            }
        }
// Cleanup
        closedir($handle);
    }
// Return the file array
    @sort($all_files);
    return $all_files;
}

//
function create_zip($files = array(), $destination = '', $overwrite = false) {
//if the zip file already exists and overwrite is false, return false  
    if (file_exists($destination) && !$overwrite) {
        return false;
    }
//vars  
    $valid_files = array();
//if files were passed in...  
    if (is_array($files)) {
//cycle through each file  
        foreach ($files as $file) {
//make sure the file exists  
            if (file_exists($file)) {
                $valid_files[] = $file;
            }
        }
    }
//if we have good files...  
    if (count($valid_files)) {
//create the archive  
        $zip = new ZipArchive();
        if ($zip->open($destination, $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
            return false;
        }
//add the files  
        foreach ($valid_files as $file) {
            $zip->addFile($file, $file);
        }
//debug  
//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;  
//close the zip -- done!  
        $zip->close();

//check to make sure the file exists  
        return file_exists($destination);
    } else {
        return false;
    }
}

//
function unzip_file($file, $destination) {
// create object  
    $zip = new ZipArchive();
// open archive  
    if ($zip->open($file) !== TRUE) {
        die('Could not open archive');
    }
// extract contents to destination directory  
    $zip->extractTo($destination);
// close archive  
    $zip->close();
    echo 'Archive extracted to directory';
}

//Find files of type
function find_files($file_extension) {
    $files = glob("*.$file_extension", GLOB_BRACE);

    print_r($files);
}

function read_csv($csvfile) {
// Let's make sure the file is there
    if (($handle = fopen($csvfile, "r")) !== FALSE) {

// This reads the the file line for line
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

// the data variable holds the whole line
            echo '<pre>';
            print_r($data);
            echo '</pre>';
        }
    }
}

function destroyDir($dir, $virtual = false) {
    $ds = DIRECTORY_SEPARATOR;
    $dir = $virtual ? realpath($dir) : $dir;
    $dir = substr($dir, -1) == $ds ? substr($dir, 0, -1) : $dir;
    if (is_dir($dir) && $handle = opendir($dir)) {
        while ($file = readdir($handle)) {
            if ($file == '.' || $file == '..') {
                continue;
            } elseif (is_dir($dir . $ds . $file)) {
                destroyDir($dir . $ds . $file);
            } else {
                unlink($dir . $ds . $file);
            }
        }
        closedir($handle);
        rmdir($dir);
        return true;
    } else {
        return false;
    }
}

function get_files_by_ext($path, $ext) {

    $files = array();

    if (is_dir($path)) {
        $handle = opendir($path);
        while ($file = readdir($handle)) {
            if ($file[0] == '.') {
                continue;
            }
            if (is_file($path . $file) and preg_match('/\.' . $ext . '$/', $file)) {
                $files[] = $file;
            }
        }
        closedir($handle);
        sort($files);
    }

    return $files;
}

//
function CalcDirectorySize($DirectoryPath) {

    // I reccomend using a normalize_path function here
    // to make sure $DirectoryPath contains an ending slash
    // (-> http://www.jonasjohn.de/snippets/php/normalize-path.htm)
    // To display a good looking size you can use a readable_filesize
    // function.
    // (-> http://www.jonasjohn.de/snippets/php/readable-filesize.htm)

    $Size = 0;

    $Dir = opendir($DirectoryPath);

    if (!$Dir)
        return -1;

    while (($File = readdir($Dir)) !== false) {

        // Skip file pointers
        if ($File[0] == '.')
            continue;

        // Go recursive down, or add the file size
        if (is_dir($DirectoryPath . $File))
            $Size += CalcDirectorySize($DirectoryPath . $File . DIRECTORY_SEPARATOR);
        else
            $Size += filesize($DirectoryPath . $File);
    }

    closedir($Dir);

    return $Size;
}

function RandomFile($folder = '', $extensions = '.*') {

    // fix path:
    $folder = trim($folder);
    $folder = ($folder == '') ? './' : $folder;

    // check folder:
    if (!is_dir($folder)) {
        die('invalid folder given!');
    }

    // create files array
    $files = array();

    // open directory
    if ($dir = @opendir($folder)) {

        // go trough all files:
        while ($file = readdir($dir)) {

            if (!preg_match('/^\.+$/', $file) and
                    preg_match('/\.(' . $extensions . ')$/', $file)) {

                // feed the array:
                $files[] = $file;
            }
        }
        // close directory
        closedir($dir);
    } else {
        die('Could not open the folder "' . $folder . '"');
    }

    if (count($files) == 0) {
        die('No files where found :-(');
    }

    // seed random function:
    mt_srand((double) microtime() * 1000000);

    // get an random index:
    $rand = mt_rand(0, count($files) - 1);

    // check again:
    if (!isset($files[$rand])) {
        die('Array index was not found! very strange!');
    }

    // return the random file:
    return $folder . $files[$rand];
}

//Writes text to a specified filename
function write_to_file($file_name, $text, $write_mode = 'ab')
{
	//Checking if the file opens successfully
	if($fh = fopen($file_name, $write_mode))
	{
		//Locking the file for writing
		flock($fh, LOCK_EX);
		
		//Writing content to the file
		fwrite($fh, $text);
		
		//Unlocking the file
		flock($fh, LOCK_UN);
		
		//Closing the file
		fclose($fh);
		return true;
	}
	else
	{
		return false;
	}
}

//Reads text one line at a time from a specified file
function read_from_file($file_name, $read_mode = 'rb')
{
	//Checking if the file opens successfully
	if($fh = fopen($file_name, $read_mode))
	{
		//Locking the file for reading
		flock($fh, LOCK_SH);
	
		//Reading from the file
		while(!eof($fh))
		{
			//Appending the text to a variable
			$line .= fgets($fh, 999) . "\n";
		}
		
		//Unlocking the file
		flock($fh, LOCK_UN);
		
		//Closing the file
		fclose($fh);
		
		//Returning the contents of the file
		return $line;
	}
	else
	{
		return false;
	}
}
?>